package cn.silver.module.monitor.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.silver.framework.core.constant.GlobalConstants;
import cn.silver.framework.excel.utils.ExcelUtil;
import cn.silver.framework.log.annotation.Log;
import cn.silver.framework.log.enums.OperateEnums;
import cn.silver.framework.mybatis.controller.BaseController;
import cn.silver.framework.openapi.model.Result;
import cn.silver.framework.redis.utils.RedisUtils;
import cn.silver.module.monitor.domain.LogLogin;
import cn.silver.module.monitor.bean.LogLoginBean;
import cn.silver.module.monitor.param.LoginParam;
import cn.silver.module.monitor.service.ILogLoginService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统访问记录
 *
 * @author Silver Zhou
 */
@Validated
@RestController
@RequiredArgsConstructor
@Tag(name = "系统监控-系统访问记录")
@RequestMapping("/monitor/login")
public class LogLoginController extends BaseController<ILogLoginService, LogLogin, LoginParam, LogLoginBean> {

    @Override
    @Resource
    public void setBaseService(ILogLoginService baseService) {
        this.baseService = baseService;
        this.setCode("monitor:login");
        this.setPermission("monitor:login");
        this.setTitle("系统监控-系统访问记录");
    }

    /**
     * 导出系统访问记录列表
     */
    @PostMapping("/export")
    @SaCheckPermission("monitor:logininfor:export")
    @Log(title = "登录日志", operate = OperateEnums.OSS_EXPORT)
    public void export(LoginParam logininfor, HttpServletResponse response) {
        List<LogLoginBean> list = baseService.selectList(logininfor);
        ExcelUtil.exportExcel(list, "登录日志", LogLoginBean.class, response);
    }

    @GetMapping("/unlock/{userName}")
    @SaCheckPermission("monitor:logininfor:unlock")
    @Log(title = "账户解锁", operate = OperateEnums.OTHER)
    public Result<Void> unlock(@PathVariable("userName") String userName) {
        if (RedisUtils.hasKey(GlobalConstants.PWD_ERR_CNT_KEY,userName)) {
            RedisUtils.deleteObject(GlobalConstants.PWD_ERR_CNT_KEY,userName);
        }
        return Result.ok();
    }

    /**
     * 清理系统访问记录
     */
    @SaCheckPermission("monitor:logininfor:remove")
    @Log(title = "登录日志", operate = OperateEnums.ALTER_DELETE)
    @DeleteMapping("/clean")
    public Result<Void> clean(@RequestBody LoginParam param) {
        baseService.cleanLogininfor(param);
        return Result.ok();
    }
}
